/**
 * 火车票封装的方法
 * @author hongwei 2018-08-03
 */
// +----------------------------------------------------------------------
// | 目录
// | step01:初始化方法                        _init
// | step02:获取火车票详情                    getTrainDetails
// | step03:点击座位产生的行为                seatClick
// | step04:打开弹窗                          openDialog
// | step05:因公为他人预定                    trainPeople
// | step06:因公为自己预定                    publicSelf
// | step07:因私预定                          privateOthers
// | step08:清除sessionStorage立面的参数      clearSessionStorage
// |
// | 1.登录页产生的参数
// | userId              : $api.getStorage('user_id'), //本人ID
// | 2.搜索页产生的参数
// | isApply             : $api.getStorage('isApply'),      //1开启申请单0关闭申请单
// | orderType           : $api.getStorage('order_type'),   //1因公0因私
// | orderSelf           : $api.getStorage('order_self'),   //2为自己3为他人
// | travelPeopleIdArray : $api.getStorage('travel_people_id_array'), //用户对象
// | 3.本站产生的storage
// | $api.setStorage("train_info", info.trainInfo);   //火车票信息
// | $api.setStorage("price", info.trainPrice);       //火车票价格
// | $api.setStorage("train_type", info.trainType);   //座位名称
// | $api.setStorage("seat_name", info.seatName);     //座位类型
// | $api.setStorage('card_submit_type',0);          //订票类型：0火车，1机票，2酒店
// | 4.因公为他人
// | $api.setStorage("reserve_type", 'other');        //single因公为自己，other因为公他人
// | $api.setStorage("order_self", 3);                //为他人，这和上边不是重复了吗？
// | 5.因公为自己
// | $api.setStorage("is_violation", is_violation);  //是否违规
// | $api.setStorage("reserve_type", 'single');      //single因公为自己，other因为公他人
// | $api.setStorage("order_self", 2);               //为自己，这和上边不是重复了吗？
// | $api.setStorage('travel_people_id_array', user_id); //用户ID
// | 6.因私
// | $api.setStorage("order_self", 1);
// +----------------------------------------------------------------------
(function (window) {
    'use strict';
    let trainMessage = function (params) {
        this.extend(this.params, params);
        this._init();
    };
    trainMessage.prototype = {
        //参数
        params: {
            //登录页产生的参数
            userId              : $api.getStorage('user_id'), //本人ID
            //搜索页产生的参数
            isApply             : $api.getStorage('isApply'),
            orderType           : $api.getStorage('order_type'), //1因公0因私
            orderSelf           : $api.getStorage('order_self'), //2为自己3为他人
            travelPeopleIdArray : $api.getStorage('travel_people_id_array'), //用户对象
            //本JS合并产生的参数
            trainInfo           : '', //火车票信息
            trainPrice          : '', //火车票价格
            trainType           : '', //座位类型
            seatName            : '', //座位名称
            end_date            : ''//到达日期
            //页面params传参
            //start_date          : '2018-08-10',
            //start_station       : '太原南',
            //end_station         : '北京',
            //train_code          : 'T102',
        },

        //step01:初始化方法
        _init: function () {
            let self = this;
            if (typeof(api) == 'undefined') {
                console.log('该插件只能在apicloud下运行');
            } else {
                self.clearMessageStorage();
                self.getTrainDetails(self.params);      //step2:获取火车票详情
                self.seatClick(self.params);                       //step3:点击座位产生的行为
            }
        },

        //清除storage
        clearMessageStorage() {
            $api.rmStorage('train_info');
            $api.rmStorage('price');
            $api.rmStorage('train_type');
            $api.rmStorage('seat_name');
        }

        //step02:获取火车票详情
        ,getTrainDetails: function (params) {
            let self = this;
            //step1：座位列表置空
            $('#seat_list').empty();
            //step2:传参获取数据
            let param = {};
            param.url = Config.api.Tickets_details;
            param.data = {
                train_start_time    : params.start_date,
                from_station_name   : params.start_station,
                to_station_name     : params.end_station,
                train_code          : params.train_code
            };
            ajax(param, function (ret) {
              console.log(JSON.stringify(ret));
                if (ret.code == 1) {
                    //显示数据
                    let res = ret.data;
                    $('.s_time').text(res.start_time);              //时间,例：22:30
                    $('.s_place').text(res.from_station_name);      //起始站,例：太原
                    $('.expenditure_time span').text(res.run_time); //时间,例：24小时30分
                    $('.e_time').text(res.arrive_time);             //到达时间：例：05:13
                    $('.e_place').text(res.to_station_name);        //到达站,例：北京
                    $('.train_code').text(params.train_code);       //车次
                    $('.run_time').text(res.run_time);              //耗时
                    var startDate = new Date(res.train_start_date.substr(0,4)+'-'+res.train_start_date.substr(4,2)+'-'+res.train_start_date.substr(6,2));
                    $('.s_date').text(res.train_start_date.substr(4,2)+'-'+res.train_start_date.substr(6,2));//开始日期
                    $('.s_week').text(getDay(startDate));            //开始日期所对应的周几
                    var endDate = new Date(res.train_arrive_date.substr(0,4)+'-'+res.train_arrive_date.substr(4,2)+'-'+res.train_arrive_date.substr(6,2));
                    $('.e_date').text(res.train_arrive_date.substr(4,2)+'-'+res.train_arrive_date.substr(6,2));//结束日期
                    $('.e_week').text(getDay(endDate));              //结束日期周几
                    $('.train_name').text(res.train_name);
                    $api.setStorage('end_date',res.train_arrive_date.substr(0,4)+'-'+res.train_arrive_date.substr(4,2)+'-'+res.train_arrive_date.substr(6,2));

                    //票列表
                    let tickets = res.tickets;
                    //获取票坐席排序
                    let html = '';
                    $.each(tickets, function (key, val) {
                        let ticketStr = '<li>无票</li>';
                        let isNo_ticket = '无票';
                        let color = '#BFBFBF';
                        let c = '';
                        if (parseInt(val.seat_num) > 20) {
                            isNo_ticket = '有票';
                            ticketStr = '<li>有票</li>';
                            color = '#FF8203';
                            c = 'type';
                        }
                        if (parseInt(val.seat_num) > 0 && parseInt(val.seat_num) <= 20) {
                            isNo_ticket = val.seat_num;
                            ticketStr = '<li style="color:#FE3F24;">'+val.seat_num+'张</li>';
                            color = '#FF8203';
                            c = 'type';
                        }
                        html += '<li><ul>';
                        html += '<li>' + val.seat_name + '</li><li style="color:#FF840B;">￥<span style="font-size:1rem;">'+val.price+'</span></li>'+ticketStr;
                        html += '<li class="' + c + '" price="' + val.price + '" seat_name="' + val.seat_name + '" train_type="' + res.train_type + '">';
                        html += '<span style="background:' + color + '">预订</span>';
                        html += '<div style="display:none" class="train_info">' + JSON.stringify(ret.data) + '</div></li>';
                        html += '</ul></li>';
                    });
                    $('#seat_list').append(html);
                } else {
                    let toast = new auiToast();
                    toast.fail({
                        title: ret.msg,
                        duration: 2000,
                    });
                    setTimeout(function () {
                        openWin('train_result', 'train_result_win.html');
                    }, 2000);
                }
            })
        },

        //step03:点击座位产生的行为
        seatClick : function(params) {
            let self = this;
            $('#seat_list').on('click' ,'.type', function(){
                //定义订票类型
                $api.setStorage('card_submit_type',0); //0火车，1机票，2酒店
                //获取当前火车票的详情
                let train_info = $(this).find('.train_info').text();
                train_info = $.parseJSON(train_info);
                train_info['end_station_name']      = params.end_station;
                train_info['start_station_name']    = params.start_station;
                train_info['train_code']            = params.train_code;
                let info = {
                    trainInfo   : JSON.stringify(train_info), //火车票信息
                    trainPrice  : $(this).attr('price'),      //火车票价格
                    seatName    : $(this).attr('seat_name'),  //座位名称
                    trainType   : $(this).attr('train_type')  //座位类型
                };
                $.extend(params, info); //合并参数

                //火车信息存储
                $api.setStorage("train_info", info.trainInfo);  //火车票信息
                $api.setStorage("price", info.trainPrice);      //火车票价格
                $api.setStorage("train_type", info.trainType);  //座位名称
                $api.setStorage("seat_name", info.seatName);    //座位类型

                //五种情况判断
                //情况1：申请单不开启，因私
                if (parseInt(params.isApply) === 0 && parseInt(params.orderType) === 0) {
                    self.privateOthers();
                }
                //情况2：申请单不开启，因公为他人因公为他人
                if (parseInt(params.isApply) === 0 && parseInt(params.orderType) === 1) {
                    self.openDialog('order_type'); //弹出
                }
                //情况3：申请单开启，因私
                if (parseInt(params.isApply) === 1 && parseInt(params.orderType) === 0) {
                    self.privateOthers();
                }
                //情况4：申请单开启，因公为本人
                if (parseInt(params.isApply) === 1 && parseInt(params.orderType) === 1 && parseInt(params.orderSelf) === 2) {
                    self.publicSelf();
                }
                //情况5：申请单开启，因公为他人
                if (parseInt(params.isApply) === 1 && parseInt(params.orderType) === 1 && parseInt(params.orderSelf) === 3) {
                    //注：这里传出四个参数：
                    //storage，card_submit_type为类型，0为火车票，前边已经设置
                    //selected_staff
                    //train_type
                    //seat_name
                    //company_staff ，陈旧的传参，可弃用
                    openWin('travel_policy_win','../common/travel_policy_win.html',{
                        train_type     : self.params.trainType           //座位类型
                        ,seat_name      : self.params.seatName            //座位名称
                    });
                }
            });
        },

        //step04:打开弹窗
        openDialog: function (type) {
            let self = this;
            let dialog = new auiDialog();
            //获取个人的差旅政策
            let param = {};
            param.url = Config.api.My_trip_policy;
            param.data = {};
            ajax(param, function (ret) {
                if (ret.code === 1) {
                    let train = ret.data.policyStr.train;
                    $('.policy').html(train);
                }
            });

            switch (type) {
                case "order_type":
                    dialog.alert({
                        title: "选择订单类型",
                        msg: $(".order_type").html(),
                        buttons: ['取消']
                    }, function (ret) {
                        console.log(ret)
                    });
                    break;
                default:
                    break;
            }
        },

        //step05:因公为他人预定
        trainPeople: function () {
            let self = this;
            $api.setStorage("reserve_type", 'other');   //single因公为自己，other因为公他人
            $api.setStorage("order_self", 3);           //为他人，这和上边不是重复了吗？
            api.openWin({
                name: 'travel_people',
                url: '../common/travel_people_frm.html',
                pageParam: {
                    train_type  : self.params.trainType,
                    seat_name   : self.params.seatName
                }
            });
        },

        //step06:因公为自己预定
        publicSelf: function (params) {
            let self = this;
            //验证当前用户是否有权限购买车票
            ajax({
                url: Config.api.Check_train_policy,
                data: {
                    userIds : self.params.userId,    //本人ID
                    seatType: self.params.trainType, //车座类型
                    seatName: self.params.seatName   //座位名称
                }
            }, function (ret) {
                if (ret.code === 1) {
                    var is_violation = ret.data[0].is_violation;
                    var violation_reservation = ret.data[0].violation_reservation; // 0为不允许违规预定 1为允许违规预定
                    if (is_violation && violation_reservation == 0) {
                        alert('当前政策标准违规,不允许违规预定');
                        return false;
                    } else {
                        $api.setStorage("is_violation", is_violation);  //是否违规
                        $api.setStorage("reserve_type", 'single');      //single因公为自己，other因为公他人
                        $api.setStorage("order_self", 2);               //为他人，这和上边不是重复了吗？
                        //add by hongwei 2018-08-02
                        $api.setStorage('travel_people_id_array', self.params.userId); //用户ID
                        openWin('submit_order_self', './submit_order_win.html');
                    }
                } else {
                    alert('验证差旅政策失败,请稍后再试');
                    return false;
                }
            }, 0, 0);
        },

        //step07:因私预定
        privateOthers: function () {
            let self = this;
            $api.setStorage("order_self", 1);
            openWin('travel_people', '../common/travel_people_frm.html');
        },

        //step08:清除sessionStorage立面的参数
        clearSessionStorage: function () {
            let self = this;
            sessionStorage.removeItem('approve_type');
            sessionStorage.removeItem('order_self');
            sessionStorage.removeItem('order_type');
            sessionStorage.removeItem('policy_execute');
            sessionStorage.removeItem('trip_policy');
            sessionStorage.removeItem('train_info');
            sessionStorage.removeItem('seat_name');
            sessionStorage.removeItem('price');
            sessionStorage.removeItem('train_type');
            sessionStorage.removeItem('selected_staff');
            sessionStorage.removeItem('selected_train');
            sessionStorage.removeItem('reserve_type');
            sessionStorage.removeItem('is_violation');
            sessionStorage.removeItem('u_type');
            sessionStorage.removeItem('u_id');
            sessionStorage.removeItem('u_index');
            sessionStorage.removeItem('cardInfo');
            sessionStorage.removeItem('policy_user_id');
            sessionStorage.removeItem('id');
            sessionStorage.removeItem('selected_cost_id');
            sessionStorage.removeItem('selected_cost_name');
            sessionStorage.removeItem('cost_info');
            sessionStorage.removeItem('selected_contact_id');
            sessionStorage.removeItem('selected_contact_name');
            sessionStorage.removeItem('selected_contact_mobile');
        },

        //step09:函数:扩展
        extend: function (a, b) {
            for (var key in b) {
                if (b.hasOwnProperty(key)) {
                    a[key] = b[key];
                }
            }
            return a;
        }
    };
    window.trainMessage = trainMessage;
})(window);
